import {store} from "../store/inedx.ts";
import {ResponseEntity} from "./types.ts";

export const getAuthorization = () => {
    return `Bearer ` + (store.getState()?.auth?.token || 'null');
}

export const getServeHost = () => {
    return '/api';
}

/**
 * 获取登录验证码
 */
export type LoginCodeResponseType = {
    image: string | null;
    loginId: string | null;
}

export const loginCode = async (): Promise<LoginCodeResponseType> => {
    const response = await fetch(`${getServeHost()}/login/code`);
    return await response.json();
}

/**
 * 管理员登录 2月25-28日
 */
export type LoginAdminReqType = {
    username: string,
    password: string,
    loginId: string,
    loginCode: string,
}
export const loginAdmin = async (request: LoginAdminReqType):Promise<ResponseEntity<string>> => {
    const response = await fetch(`${getServeHost()}/login/admin`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': getAuthorization(),
        },
        body: JSON.stringify(request),
    });
    return await response.json();
}

/**
 * 获取命名空间列表
 */
export interface NamespaceSelectEntity {
    uid: string;
    createdAt: string;
    updatedAt: string;
    name: string;
    label: string;
    status: boolean;
}

export const namespaceList = async (): Promise<ResponseEntity<NamespaceSelectEntity[]>> => {
    const response = await fetch(`${getServeHost()}/namespace-list`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': getAuthorization(),
        },
        body: JSON.stringify({current: 1, size: 1000}),
    });
    return await response.json();
}

export const namespaceDelete = async (entity: NamespaceSelectEntity): Promise<ResponseEntity<NamespaceSelectEntity>> => {
    const response = await fetch(`${getServeHost()}/namespace-delete`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': getAuthorization(),
        },
        body: JSON.stringify(entity),
    });
    return await response.json();
}

export const namespaceSave = async (entity: NamespaceSelectEntity): Promise<ResponseEntity<NamespaceSelectEntity>> => {
    const response = await fetch(`${getServeHost()}/namespace-save`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': getAuthorization(),
        },
        body: JSON.stringify(entity),
    });
    return await response.json();
}

export const namespaceUpdate = async (entity: NamespaceSelectEntity): Promise<ResponseEntity<NamespaceSelectEntity>> => {
    const response = await fetch(`${getServeHost()}/namespace-update`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': getAuthorization(),
        },
        body: JSON.stringify(entity),
    });
    return await response.json();
}